package cn.elwy.rcp.ui.table.setting.listener;

import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TreeColumn;

import cn.elwy.rcp.ui.table.TablePane;
import cn.elwy.rcp.ui.table.util.ColumnVisibleUtil;

public class ColumnResizeListener implements ControlListener {

  private static final int MIN_WIDTH = 0;
  private boolean loop;
  protected TablePane tablePane;

  public ColumnResizeListener() {
  }

  @Override
  public void controlMoved(ControlEvent e) {
    handColumnEvent(e);
  }

  @Override
  public void controlResized(ControlEvent e) {
    handColumnEvent(e);
  }

  private void handColumnEvent(ControlEvent e) {
    if (loop) {
      return;
    }
    if (e.widget instanceof TreeColumn) {
      TreeColumn column = (TreeColumn) e.widget;
      int width = column.getWidth();
      if (column.getResizable()) {
        if (width <= MIN_WIDTH) {
          loop = true;
          column.setWidth((Integer) column.getData(ColumnVisibleUtil.DEFAULT_COLUMN_WIDTH));
          ColumnVisibleUtil.setColumnVisible(column, false);
          loop = false;
        } else {
          column.setData(ColumnVisibleUtil.COLUMN_WIDTH, width);
        }
      }
    } else {
      TableColumn column = (TableColumn) e.widget;
      int width = column.getWidth();
      if (column.getResizable()) {
        if (width <= MIN_WIDTH) {
          loop = true;
          column.setWidth((Integer) column.getData(ColumnVisibleUtil.DEFAULT_COLUMN_WIDTH));
          ColumnVisibleUtil.setColumnVisible(column, false);
          loop = false;
        } else {
          column.setData(ColumnVisibleUtil.COLUMN_WIDTH, width);
        }
      }
    }
    tablePane.setConfigChanged(true);
  }

  public TablePane getTablePane() {
    return tablePane;
  }

  public void setTablePane(TablePane tablePane) {
    this.tablePane = tablePane;
  }

}
